搜索 K
Appearance
博客正在加载中...
Appearance
注解 @ConfigurationProperties 可以读取到 properties 文件中的内容,并且把它封装到 JavaBean 中,以供随时使用
我们经常将一些频繁变化的信息,放到配置文件中,例如数据库连接信息;
然后在项目启动的时候,就读取配置文件,并加载,还是比较麻烦的,需要手工读取和赋值:
public class getProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties pps = new Properties();
pps.load(new FileInputStream("a.properties"));
Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
while(enum1.hasMoreElements()) {
String strKey = (String) enum1.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
//封装到JavaBean...........
}
}
} 当配置增多,那么代码就会更复杂,可能还得用正则;而在 SpringBoot 中就很方便。演示:
package com.peterjxl.boot.bean;
public class Car {
private String brand;
private Integer price;
}getter 和 setter 自行生成
我们在 application.properties 里增加汽车的配置:
server.port=9999
spring.servlet.multipart.max-file-size=10MB
mycar.brand=BYD
mycar.price=100000
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {说明:
我们新增一个 Controller 方法,返回 car 对象:
package com.peterjxl.boot.controller;
@RestController // @RestController = @Controller + @ResponseBody
public class HelloController {
@Autowired
Car car;
@RequestMapping("/car")
public Car car() {
return car;
}
@RequestMapping("/hello")
public String hello() {
return "你好, Spring Boot 2!";
}
} 访问 localhost: 9999/car,可以看到对象的信息
我们还可以使用这个两个注解来完成配置绑定:
@EnableConfigurationProperties + @ConfigurationProperties 首先,我们在一个配置类上使用@EnableConfigurationProperties。注意,要传入 Car 对象的字节码,如:
@EnableConfigurationProperties(Car.class)
public class MyConfig { 然后,car 对象就不用@Component 注解了,配置类会自动导入 car 组件:
//@Component
@ConfigurationProperties(prefix = "mycar")
public class Car { 这样,我们就不用再使用@Component 注解了。这有什么用呢?有时候,我们要配置绑定的类,是第三方 jar 包的类,此时就可以用这种方式。
在 SpringBoot 底层,我们会经常看到该注解